package com.deer.wms.base.system.service.MESWebService;

//import org.apache.cxf.endpoint.Client;
//import org.apache.cxf.endpoint.Endpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deer.wms.base.system.dao.BillDetailMapper;
import com.deer.wms.base.system.dao.BillInfoMapper;
import com.deer.wms.base.system.dao.ItemInfoMapper;
import com.deer.wms.base.system.model.BillContDetailBO;
import com.deer.wms.base.system.model.BillContainerBO;
import com.deer.wms.base.system.model.BillDetail;
import com.deer.wms.base.system.model.BillInfo;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Item.ItemInfoBO;
import com.deer.wms.project.root.util.HttpClient;
import org.apache.commons.codec.binary.Base64;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/*import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;*/
/*import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.types.GrantType;

/**
 * Created by  on 2019/09/26.
 */
@Service //
public class ServerVisitAddressServiceImpl implements ServerVisitAddressService {





    /* @Override
    public EbsBack requestItemId(String itemCode,Integer organizationId)
    {
        CloseableHttpClient client = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        //获取token的地址及账号密码
        ServerVisitAddress serverVisitAddressFour = serverVisitAddressMapper.findAddressById(4);
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        try {
            OAuthClientRequest accessTokenRequest = OAuthClientRequest
                    .tokenLocation(serverVisitAddressFour.getVisitAddress())
                    .setGrantType(GrantType.CLIENT_CREDENTIALS)
                    .setUsername(serverVisitAddressFour.getAccount())
                    .setPassword(serverVisitAddressFour.getPassword())
                    .buildQueryMessage();
            accessTokenRequest.addHeader("Accept", "application/json");
            accessTokenRequest.addHeader("Content-Type", "application/json");
            String auth = MyUtils.encode(serverVisitAddressFour.getAccount() + ':' + serverVisitAddressFour.getPassword());
            accessTokenRequest.addHeader("Authorization", "Basic " + auth);
            OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST); //去服务端请求access_token，并返回响应
            String accessToken = oAuthResponse.getAccessToken(); //获取服务端返回过来的access_token
            //获取EBS请求接口地址
            ServerVisitAddress serverVisitAddressThree = serverVisitAddressMapper.findAddressById(5);
            HttpPost httpPost = new HttpPost(serverVisitAddressThree.getVisitAddress());
            httpPost.setHeader("Authorization","bearer "+accessToken);
            httpPost.setHeader("Content-Type","application/json");
            SystemParams systemParams = new SystemParams("1","PCB_APS","APS","EBS",
                    "getInvItemInfosForPcbAps",MyUtils.randomAssignFigures(6),System.currentTimeMillis(),
                    TaskTypeConstant.QUERY,"1.0","fd");
            BaseQueryParams2 baseQueryParams = new BaseQueryParams2(
                organizationId,"2000-01-01",DateUtils.getDate(),1,50
            );
            *//*List<Map<String, String>> baseQueryParams = new ArrayList<>();
            Map<String, String> map1 = new HashMap<>();
            map1.put("organizationId",organizationId.toString());
            map1.put("lastUpdateDateF","2000-01-01");
            map1.put("lastUpdateDateT",DateUtils.getDate());
            map1.put("startPosition","1");
            map1.put("rowsCnt","50");
            baseQueryParams.add(map1);*//*
            List<Map<String, String>> lists = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            map.put("itemCode",itemCode);
            lists.add(map);
//            systemParams.setToken(accessToken);
            Body2 body2 = new Body2(systemParams, baseQueryParams,lists);
            String listJson = JSON.toJSONString(body2);
            StringEntity stringEntity = new StringEntity(listJson,"UTF-8");
            httpPost.setEntity(stringEntity);
            response = client.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(entityStr);
            String success = jsonObject.get("success").toString().trim();
            String msg = jsonObject.get("msg").toString().trim();
            Integer total = null;
            String rows = "";
            if(success.equals("true")) {
                String obj = jsonObject.get("obj").toString().trim();
                JSONObject jsonObject1 = JSONObject.parseObject(obj);
                total = jsonObject1.get("total").toString().trim() == null ? 0 : Integer.parseInt(jsonObject1.get("total").toString().trim());
                rows = jsonObject1.get("rows").toString().trim();
            }
            return new EbsBack(success,msg,total,rows);
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    client.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        return null;
    }*/
   /* public EbsBack requestServerCode(String requestId, String serviceName, String serviceOperation, Integer organizationId,List<Map<String, String>> lists)
            {
        CloseableHttpClient client = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        //获取token的地址及账号密码
        ServerVisitAddress serverVisitAddressFour = serverVisitAddressMapper.findAddressById(4);
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        try {
            OAuthClientRequest accessTokenRequest = OAuthClientRequest
                    .tokenLocation(serverVisitAddressFour.getVisitAddress())
                    .setGrantType(GrantType.CLIENT_CREDENTIALS)
                    .setUsername(serverVisitAddressFour.getAccount())
                    .setPassword(serverVisitAddressFour.getPassword())
                    .buildQueryMessage();
            accessTokenRequest.addHeader("Accept", "application/json");
            accessTokenRequest.addHeader("Content-Type", "application/json");
            String auth = MyUtils.encode(serverVisitAddressFour.getAccount() + ':' + serverVisitAddressFour.getPassword());
            accessTokenRequest.addHeader("Authorization", "Basic " + auth);
            OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST); //去服务端请求access_token，并返回响应
            String accessToken = oAuthResponse.getAccessToken(); //获取服务端返回过来的access_token
            //获取EBS请求接口地址
            ServerVisitAddress serverVisitAddressThree = serverVisitAddressMapper.findAddressById(3);
            HttpPost httpPost = new HttpPost(serverVisitAddressThree.getVisitAddress());
            httpPost.setHeader("Authorization","bearer "+accessToken);
            httpPost.setHeader("Content-Type","application/json");
            SystemParams systemParams = new SystemParams(requestId,"NT_WMS","NT_WMS","EBS",
                    serviceName,MyUtils.randomAssignFigures(6),System.currentTimeMillis(),
                    serviceOperation,"1.0","");
            String listJson = "";
            if(organizationId != null) {
                BaseQueryParams baseQueryParams = new BaseQueryParams(organizationId);
                Body body = new Body(systemParams,baseQueryParams,lists);
                listJson = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);
            }else{
                BaseQueryParams1 baseQueryParams = new BaseQueryParams1();
                Body1 body = new Body1(systemParams,baseQueryParams,lists);
                listJson = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);
            }
//            systemParams.setToken(accessToken);
            StringEntity stringEntity = new StringEntity(listJson,"UTF-8");
            httpPost.setEntity(stringEntity);
            response = client.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(entityStr);
            String success = jsonObject.get("success").toString().trim();
            String msg = jsonObject.get("msg").toString().trim();
            Integer total = null;
            String rows = "";
            if(success.equals("true")) {
                String obj = jsonObject.get("obj").toString().trim();
                JSONObject jsonObject1 = JSONObject.parseObject(obj);
                total = jsonObject1.get("total").toString().trim() == null ? 0 : Integer.parseInt(jsonObject1.get("total").toString().trim());
                rows = jsonObject1.get("rows").toString().trim();
            }
            return new EbsBack(success,msg,total,rows);
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    client.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
*/

//    public static Map<String,Endpoint> factoryMap=new HashMap<String, Endpoint>();
//    public static Map<String,Client> clientMap=new HashMap<String, Client>();

    /**
     * 给mes发送请求
     * @param methodName
     * @param code
     * @return
     */
    @Override
    public WebserviceResponse requestMesServerOne(String methodName, String code) {
        WebserviceResponse webserviceResponse = null;
//        try{
//            Object[] objects;
//
//            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//            //访问MES的地址，此地址是MES那边定义的，   给的时候如果没有?wsdl就要加上，有就不需要
//            Client client = dcf.createClient("http://192.168.0.100:9090/wsservice/macWS?wsdl");
//            objects = client.invoke("macIntf", methodName,code);
//            webserviceResponse = analysisObject(objects[0]);
////            System.out.println("返回数据:" + objects[0].toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            webserviceResponse = new WebserviceResponse(null,"-1","调用WMS接口出错",null);
//        }
        return webserviceResponse;
    }
    @Override
    public WebserviceResponse requestMesServerTwo(String methodName, String code) {
        WebserviceResponse webserviceResponse = null;
//        try{
//            Object[] objects;
//            if(!factoryMap.containsKey(methodName)) {
//                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//                //访问MES的地址，此地址是MES那边定义的，   给的时候如果没有?wsdl就要加上，有就不需要
//                Client client = dcf.createClient("http://192.168.0.100:9090/wsservice/macWS?wsdl");
//                Endpoint endpoint = client.getEndpoint();
//                factoryMap.put(methodName,endpoint);
//                clientMap.put(methodName,client);
//                System.out.println("初始化");
//            }
//            Client client = clientMap.get(methodName);
//            Endpoint endpoint = factoryMap.get(methodName);
//            QName qname = new QName(endpoint.getService().getName().getNamespaceURI(), "macIntf");
//            BindingInfo bingdingInfo = endpoint.getEndpointInfo().getBinding();
//            if (bingdingInfo.getOperation(qname) == null) {
//                for (BindingOperationInfo operationInfo : bingdingInfo.getOperations()) {
//                    if ("macIntf".equals(operationInfo.getName().getLocalPart())) {
//                        qname = operationInfo.getName();
//                        break;
//                    }
//                }
//            }
//            objects = client.invoke(qname, methodName, code);
//            webserviceResponse = analysisObject(objects[0]);
//                        System.out.println("返回数据:" + objects[0].toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            webserviceResponse = new WebserviceResponse(null,"-1","调用WMS接口出错",null);
//        }
        return webserviceResponse;
    }
    @Override
    public WebserviceResponse requestMesServerThree(String methodName, String code) {
        WebserviceResponse webserviceResponse = null;
//        try{
//            Object[] objects;
//            if(!clientMap.containsKey(methodName)) {
//                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//                //访问MES的地址，此地址是MES那边定义的，   给的时候如果没有?wsdl就要加上，有就不需要
//                Client client = dcf.createClient("http://192.168.0.100:9090/wsservice/macWS?wsdl");
//                clientMap.put(methodName,client);
//                System.out.println("初始化");
//            }
//            Client client = clientMap.get(methodName);
//            QName qname = new QName("http://scc.com.cn", "macIntf");
//            objects = client.invoke(qname, methodName, code);
//            webserviceResponse = analysisObject(objects[0]);
//            System.out.println("返回数据:" + objects[0].toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            webserviceResponse = new WebserviceResponse(null,"-1","调用WMS接口出错",null);
//        }
        return webserviceResponse;
    }


    public WebserviceResponse analysisObject(Object object) throws Exception{
        Field taskCode = object.getClass().getDeclaredField("x003CTaskCodeX003EKBackingField");
        taskCode.setAccessible(true);
        Field errorCode = object.getClass().getDeclaredField("x003CErrorCodeX003EKBackingField");
        errorCode.setAccessible(true);
        Field errorMsg = object.getClass().getDeclaredField("x003CErrorMsgX003EKBackingField");
        errorMsg.setAccessible(true);
        Field resultData = object.getClass().getDeclaredField("x003CResultDataX003EKBackingField");
        resultData.setAccessible(true);
        String taskCode1 = taskCode.get(object) == null?"":taskCode.get(object).toString();
        String errorCode1 = errorCode.get(object).toString();
        String errorMsg1 =  errorMsg.get(object).toString();
        String resultData1 = resultData.get(object)==null?"":resultData.get(object).toString();
        WebserviceResponse webserviceResponse = new WebserviceResponse(taskCode1,errorCode1, errorMsg1, resultData1);
        return webserviceResponse;
    }

    @Override
    public WebserviceResponse requestMesServerFour(String methodName, String code) {
        WebserviceResponse webserviceResponse = null;
        try{
//            Object[] objects;
            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
            //访问MES的地址，此地址是MES那边定义的，   给的时候如果没有?wsdl就要加上，有就不需要
            Client client = dcf.createClient("http://192.168.0.100:9090/wsservice/macWS?wsdl");

        } catch (Exception e) {
            e.printStackTrace();
            webserviceResponse = new WebserviceResponse(null,"-1","调用WMS接口出错",null);
        }
        return webserviceResponse;
    }

    @Override
    public void itemToContainer() {

        //查询未推送到智能货柜的数据
        ItemInfoMapper itemInfoMapper = ApplicationContextUtil.getBean(ItemInfoMapper.class);
        QueryWrapper<ItemInfo> qw = Wrappers.query();
        List<ItemInfo> itemInfos = itemInfoMapper.selectList(qw.ne("is_transmit", 1));
        //将查询到的数据进行处理
        List<ItemInfoBO> bos = new ArrayList<>();
        for(ItemInfo itemInfo : itemInfos){
            ItemInfoBO itemInfoBO = new ItemInfoBO();
            itemInfoBO.setART_ARTICOLO(itemInfo.getItemCode());
            itemInfoBO.setART_DES(itemInfo.getItemName());
            itemInfoBO.setART_UMI(itemInfo.getUnitName());
            itemInfoBO.setART_NOTE(itemInfo.getSpec());
            bos.add(itemInfoBO);
        }
        //判断是否存在未推送到智能货柜的数据
        if(bos.size() > 0){
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost("http://127.0.0.1:3001/api/jobs/CFG-IMP-ARTICOLI");
//            System.out.println("要发送的数据" + JSON.toJSONString(bos));
            StringEntity myEntity = new StringEntity(JSON.toJSONString(bos), ContentType.APPLICATION_JSON);// 构造请求数据
            post.addHeader("Authorization", HttpClient.getHeader());
            post.setEntity(myEntity);// 设置请求体
            String responseContent = null; // 响应内容
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
//                System.out.println(JSON.toJSONString(response));
                if (response.getStatusLine().getStatusCode() == 200) {
//                    System.out.println("sucess");
                    //修改推送到智能货柜的数据状态
                    for(ItemInfo itemInfo : itemInfos){
                        itemInfo.setIsTransmit("1");
                        itemInfoMapper.updateById(itemInfo);
                    }
                }
//                System.out.println("responseContent:" + responseContent);
            } catch (Exception e) {
                e.printStackTrace();
            }  finally {
                try {
                    if (response != null)
                        response.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (client != null)
                            client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }

    @Override
    public void billToContainer() {

        //查询未推送到智能货柜的数据
        BillInfoMapper billInfoMapper = ApplicationContextUtil.getBean(BillInfoMapper.class);
        QueryWrapper<BillInfo> qw = Wrappers.query();
        List<BillInfo> billInfos = billInfoMapper.selectList(qw.ne("is_transmit", 1));

        //将查询到的数据进行处理
        List<BillContainerBO> bos = new ArrayList<>();
        for(BillInfo billInfo : billInfos){
            BillContainerBO billContainerBO = new BillContainerBO();
            BillDetailMapper billDetailMapper = ApplicationContextUtil.getBean(BillDetailMapper.class);
            QueryWrapper<BillDetail> qw2 = Wrappers.query();
            List<BillDetail> bds = billDetailMapper.selectList(qw2.eq("bill_info_id", billInfo.getId()));
            List<BillContDetailBO> dbs = new ArrayList<>();
            for(BillDetail billDetail : bds){
                BillContDetailBO billContDetailBO = new BillContDetailBO();
                billContDetailBO.setRIG_SUB1(billDetail.getBatchNo());
                //季工说字段要做调整，目前字段还没定
                dbs.add(billContDetailBO);
            }

            billContainerBO.setORD_TIPOOP(billInfo.getBillTypeId().toString());
            billContainerBO.setDetails(dbs);
            bos.add(billContainerBO);
        }
        //判断是否存在未推送到智能货柜的数据
        if(bos.size() > 0){
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost("http://127.0.0.1:3001/api/jobs/CFG-IMP-ARTICOLI");
//            System.out.println("要发送的数据" + JSON.toJSONString(bos));
            StringEntity myEntity = new StringEntity(JSON.toJSONString(bos), ContentType.APPLICATION_JSON);// 构造请求数据
            post.addHeader("Authorization", HttpClient.getHeader());
            post.setEntity(myEntity);// 设置请求体
            String responseContent = null; // 响应内容
            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
//                System.out.println(JSON.toJSONString(response));
                if (response.getStatusLine().getStatusCode() == 200) {
//                    System.out.println("sucess");
                    //修改推送到智能货柜的数据状态
                    for(BillInfo billInfo : billInfos){
                        billInfo.setIsTransmit("1");
                        billInfoMapper.updateById(billInfo);
                    }
                }
//                System.out.println("responseContent:" + responseContent);
            } catch (Exception e) {
                e.printStackTrace();
            }  finally {
                try {
                    if (response != null)
                        response.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (client != null)
                            client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

}
